<?php
namespace App\BaseExt;
use Symfony\Component\HttpFoundation\Request;

/**
 * PicUpload Class
 */
class PicUpload {

    /*params inner*/
    private $maxSize    = 2097152;//文件大小限制,单位B,默认2M

    /*params outer*/
    private $uploadDir  = "default";//默认上传目录
    private $maxWidth   = 5000;//文件宽度限制
    private $maxHeight  = 5000;//文件高度限制

    /*Success Data*/
    private $sucessData;

    public function getParamRequired($paramName)
    {
        $request = Request::createFromGlobals();
        if ($request->request->has("$paramName")) {
            return $request->get("$paramName");
        }
        if ($request->query->has("$paramName")) {
            return $request->get("$paramName");
        }
        return false;
    }
    /*
     * 使用说明：
     *  传参：$postName,如果只为一个字段获取可以为字符串也可以为数组如“pic",array("pic")，如果为多个字段获取应设置为数组如array("pic1"，"pic2")
     *  返回：$return,
     *          如果过程发生错误,则返回数组：s=0，i=错误信息，d=空；
     *          如果正确则返回相应的数组：array("pic1"=>array(DATA)),DATA根据上传字段数量不同，
     *                  一个字段一个图片的DATA为：s=0，i=上传成功，d=空；
     *                  一个字段多个图片的DATA[]为：s=0，i=上传成功，d=空；
     * */
    /**
     * @param array|string $postName
     * @return array
     */
    public function doUpload($postName)
    {
//        $request = Request::createFromGlobals();
        //检查上传图片数量是否与获取意图一致
        if (is_string($postName)) {
            $postName = array($postName);
        }
        sort($postName);
        $postKeys = array_keys($_FILES);
        sort($postKeys);
        if ($postName !== $postKeys || $postKeys == "") {
            return array(
                "s" => 0,
                "i" => "上传数量与要求数量不一致",
                "d" => json_encode($_FILES),
            );
        }
        //重构$_FILES变量，依次上传单个文件
        //注：每个FILENAME为一个结果集，如果FILENAME[]为数组，则返回一个数组格式的结果，对应每一个上传文件
        $orgFileData = $_FILES;
        $return = array();
        foreach ($postKeys as $filePostName) {
            $_FILES =array();
            $name = $orgFileData[$filePostName]["name"];
            if (is_array($name)) {//数组格式上传的图片组即FILENAME[]
                foreach ($name as $k => $v) {
                    $_FILES[$filePostName] = array(
                        'name'      =>  $orgFileData[$filePostName]["name"][$k] ,
                        'type'      =>  $orgFileData[$filePostName]["type"][$k] ,
                        'tmp_name'  =>  $orgFileData[$filePostName]["tmp_name"][$k] ,
                        'error'     =>  $orgFileData[$filePostName]["error"][$k] ,
                        'size'      =>  $orgFileData[$filePostName]["size"][$k] ,
                    );
                    if ($orgFileData[$filePostName]["size"][$k] > $this->maxSize) {
                        return array(
                            "s" => 0,
                            "i" => "文件大小超出限制，最大为".($this->maxSize / 1024 )."KB",
                            "d" => "",
                        );
                    }
                    $rst = $this->single($filePostName);
                    $return[$filePostName][$k]=$rst;
                }
            } else {//一个文件对应一个FILENAME
                $_FILES[$filePostName] = array(
                    'name'      =>  $orgFileData[$filePostName]["name"] ,
                    'type'      =>  $orgFileData[$filePostName]["type"] ,
                    'tmp_name'  =>  $orgFileData[$filePostName]["tmp_name"] ,
                    'error'     =>  $orgFileData[$filePostName]["error"] ,
                    'size'      =>  $orgFileData[$filePostName]["size"] ,
                );
                if ($orgFileData[$filePostName]["size"] > $this->maxSize) {
                    return array(
                        "s" => 0,
                        "i" => "文件大小超出限制，最大为".($this->maxSize / 1024 )."KB",
                        "d" => "",
                    );
                }
                $rst = $this->single($filePostName);
                $return[$filePostName]=$rst;
            }
        }
        $this->sucessData = $return;
        return $return;
    }

    public function single($postName){
        $request = Request::createFromGlobals();
        //获取参数
        if (!$uploadDir  = $this->getParamRequired("uploadDir",$request)) {$uploadDir = $this->uploadDir;}
        if (!$max_height = $this->getParamRequired("maxWidth",$request)) {$max_height = $this->maxWidth;}
        if (!$max_wight  = $this->getParamRequired("maxHeight",$request)) {$max_wight = $this->maxHeight;}
        //检查上传格式是否正确
        if(!isset($_FILES[$postName])) {
            return array(
                's'=>0,
                'i'=>'未选择图片!',
                "d"=>""
            );
        }
        if (!isset($_FILES[$postName]['error']) || $_FILES[$postName]['error']===4) {
            return array(
                's'=>0,
                'i'=>'未选择图片!',
                "d"=>""
            );
        }
        //尝试上传
        $file = $request->files->get($postName);
        $fileName = md5(time().uniqid()).'.'.$file->guessExtension();
        $absPath = './uploads/'.$uploadDir.'/'.date("Ymd");
        $file->move($absPath, $fileName);
        //检查像素宽高限制，超出限制的清除文件
        $filePath = "/uploads/".$uploadDir."/".date("Ymd")."/".$fileName;
        $realPath = $absPath."/".$fileName;
        $info = getimagesize($realPath);
        $image_width = $info[0];
        $image_height = $info[1];
        if ($max_height!=0 || $max_wight!=0) {
            if ($image_height > $max_height) {
                unlink($realPath);
                return array(
                    's'=>0,
                    'i'=>'图片过大,高度不可超过'.$max_height.'像素!',
                    "d"=>""
                );
            }
            if($image_width > $max_wight){
                unlink($realPath);
                return array(
                    's'=>0,
                    'i'=>'图片过大,宽度不可超过'.$max_wight.'像素!',
                    "d"=>""
                );
            }
        }
        return array(
            's'=>1,
            'i'=>'上传成功!',
            "d"=>$filePath
        );
    }

    public function multiUpload($postName){
        $request = Request::createFromGlobals();
        //获取参数
        if (!$uploadDir  = $this->getParamRequired("uploadDir",$request)) {$uploadDir = $this->uploadDir;}
        if (!$max_height = $this->getParamRequired("maxWidth",$request)) {$max_height = $this->maxWidth;}
        if (!$max_wight  = $this->getParamRequired("maxHeight",$request)) {$max_wight = $this->maxHeight;}
        //检查上传格式是否正确
        if(!isset($_FILES[$postName])) {
            return array(
                's'=>0,
                'i'=>'未选择图片!',
                "d"=>""
            );
        }
        if (!isset($_FILES[$postName]['error']) || $_FILES[$postName]['error']===4) {
            return array(
                's'=>0,
                'i'=>'未选择图片!',
                "d"=>""
            );
        }
        //尝试上传
        $files = $request->files->get($postName);
        $filePath = [];
        foreach ($files as $file) {

            $fileName = md5(time().uniqid()).'.'.$file->guessExtension();
            $absPath = './uploads/'.$uploadDir.'/'.date("Ymd");
            $file->move($absPath, $fileName);
            //检查像素宽高限制，超出限制的清除文件
            $filePath[] = "/uploads/".$uploadDir."/".date("Ymd")."/".$fileName;
            $realPath = $absPath."/".$fileName;
            $info = getimagesize($realPath);
            $image_width = $info[0];
            $image_height = $info[1];
            if ($max_height!=0 || $max_wight!=0) {
                if ($image_height > $max_height) {
                    unlink($realPath);
                    return array(
                        's'=>0,
                        'i'=>'图片过大,高度不可超过'.$max_height.'像素!',
                        "d"=>""
                    );
                }
                if($image_width > $max_wight){
                    unlink($realPath);
                    return array(
                        's'=>0,
                        'i'=>'图片过大,宽度不可超过'.$max_wight.'像素!',
                        "d"=>""
                    );
                }
            }
        }
        return array(
            's'=>1,
            'i'=>'上传成功!',
            "d"=>$filePath
        );
    }

    public function getData(){
        if ( $this->sucessData ) {
            $return = array();
            foreach ($this->sucessData as $fieldName => $picsData) {
                if (isset($picsData["s"])) {
                    $return[$fieldName] = $picsData["d"];
                } else {
                    if (!is_array($picsData) || empty($picsData)) {
                        return false;
                    }
                    $pics = array();
                    foreach ($picsData as $k=>$picData) {
                        if (isset($picData["s"]) && $picData["s"] == 1) {
                            $pics[] = $picData["d"];
                        }
                    }
                    $return[$fieldName] = $pics;
                }
            }
            return $return;
        }
        return false;
    }
}
